package com.hh.manager;

import com.hh.entity.domain.User;
import com.hh.entity.dto.blog.BlogAddRequest;
import com.hh.service.BlogService;
import com.hh.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * com.hh.manager
 *
 * @author hanhui
 * @version 1.0
 * @since 2025/9/8 20:13
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class MarkdownService {

    private final UserService userService;
    private final BlogService blogService;

    /**
     * 批量处理上传的Markdown文件
     */
    @Async
    public CompletableFuture<List<String>> processMarkdownFiles(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        List<String> results = new ArrayList<>();

        for (MultipartFile file : files) {
            try {
                // 验证文件是否为markdown
                if (!isMarkdownFile(file.getOriginalFilename())) {
                    results.add("文件 " + file.getOriginalFilename() + " 不是Markdown文件，已跳过");
                    continue;
                }
                // 读取文件内容
                String content = readFileContent(file);
                // 提取标题（假设第一行为标题）
                String title = extractTitle(content);
                log.info("md解析：title:{},content:{}", title, content);
                BlogAddRequest blogAddRequest = new BlogAddRequest();
                blogAddRequest.setTitle(title);
                blogAddRequest.setContent(content);
                blogService.addBlog(blogAddRequest,loginUser);
                results.add("文件 " + file.getOriginalFilename() + " 处理成功");
            } catch (Exception e) {
                results.add("文件 " + file.getOriginalFilename() + " 处理失败: " + e.getMessage());
            }
        }

        return CompletableFuture.completedFuture(results);
    }

    /**
     * 检查文件是否为markdown文件
     */
    private boolean isMarkdownFile(String fileName) {
        if (fileName == null) {
            return false;
        }
        String lowerFileName = fileName.toLowerCase();
        return lowerFileName.endsWith(".md") || lowerFileName.endsWith(".markdown");
    }

    /**
     * 读取文件内容
     */
    private String readFileContent(MultipartFile file) throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        }
        return content.toString();
    }

    /**
     * 提取标题（简单处理，实际可能需要更复杂的逻辑）
     */
    private String extractTitle(String content) {
        // 尝试从内容中提取标题
        String[] lines = content.split("\n");
        for (String line : lines) {
            if (line.startsWith("# ")) {
                return line.substring(2).trim();
            }
        }
        // 如果没有找到标题，返回"无标题"
        return "无标题";
    }
}
